package com.project.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.project.bean.CommentBean;
import com.project.bean.FolloweBean;
import com.project.bean.PageBean;
import com.project.bean.PostBean;
import com.project.dao.FollowMapper;
import com.project.dao.PostMapper;
import com.project.service.IPostService;
import com.project.util.DateUtil;

@Service(value = "postService")
public class PostServiceImpl implements IPostService{

	@Autowired
	private PostMapper postMapper;
	
	@Autowired
	private FollowMapper followMapper;


	@Override
	public int addPost(PostBean post) {
		
		return postMapper.insert(post);
	}

	@Override
	public int deletePost(Integer id) {
		// TODO Auto-generated method stub
		return postMapper.deleteByPrimaryKey(id);
	}

	@Override
	public PostBean findPostById(Integer id) {
		// TODO Auto-generated method stub
		return postMapper.selectByPrimaryKey(id);
	}

	@Override
	public PageBean findUserPostsByPage(Integer id, Integer page, Integer size) {
		PageBean pageBean=new PageBean();
		Map<String,Integer> map=new HashMap<String,Integer>();
		map.put("page", (page-1)*size);
		map.put("size", size);
		map.put("uid", id);
		List<PostBean> list=postMapper.findPostsByPage(map);
		for (PostBean postBean : list) {
			Date date=postBean.getpTime();
			String time=DateUtil.changeTime(date);
			postBean.setpDate(time);
		}
		
		int num=postMapper.findAllByUid(id);
		int totalpage=(num%size==0)?(num/size):(num/size+1);
		pageBean.setPage(page);
		pageBean.setSize(size);
		pageBean.setTotalNumber(num);
		pageBean.setTotalPage(totalpage);
		pageBean.setList(list);
		return pageBean;
	}

	@Override
	public PageBean findAllFollowPosts(Integer id, Integer page, Integer size) {
		PageBean pageBean=new PageBean();	
		List<FolloweBean> flist=followMapper.findFollowsById(id);
		
		List<Integer> fuids=new ArrayList<Integer>();
		int num=0;	
		for (FolloweBean followeBean : flist) {
			 Integer fUid = followeBean.getfUId2();
			 num+=postMapper.findAllByUid(fUid); 
			 fuids.add(fUid);
		}		
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("page", (page-1)*size);
		map.put("size", size);
		map.put("list", fuids);
		List<PostBean> list=postMapper.findFollowPostsByPage(map);
		for (PostBean postBean : list) {
		 Date date=postBean.getpTime();
		 String time=DateUtil.changeTimes(date);
		 postBean.setpDate(time);
		}
		int totalpage=(num%size==0)?(num/size):(num/size+1);
		pageBean.setPage(page);
		pageBean.setSize(size);
		pageBean.setTotalNumber(num);
		pageBean.setTotalPage(totalpage);
		pageBean.setList(list);
		return pageBean;
	}
	}
	

